const fs = require('fs')
const path = require('path')
const uuid = require('uuid')
const { spawn, exec } = require('child_process')

// 读文件
const readFile = (filePath, parseJson = false) => {
    if (!filePath) {
        return ''
    }
    let str = fs.readFileSync(filePath, { encoding: 'UTF-8' })
    if (parseJson) {
        try {
            return JSON.parse(str)
        } catch (e) {
            return str
        }
    }
    return str
}

// 写文件
const writeFile = (filePath, text = '') => {
    if (filePath) {
        let dirPath = path.resolve(filePath, '../')
        if (!fs.existsSync(dirPath)) {
            fs.mkdirSync(dirPath)
        }
        fs.writeFileSync(filePath, text)

    }
}

// 执行命令
const runShell = (command, args, output = false) => {
    const platform = process.platform.toLowerCase()

    return new Promise((reslove, reject) => {
        if (platform == 'win32') {
            let cmd = command + ' ' + [...args].join(' ')
            const execRes = exec(cmd, {
                encoding: 'UTF-8'
            })
            if (output) {
                execRes.stdout.on('data', (data) => {
                    console.log(`${data}\n`)
                })
                execRes.stderr.on('data', (data) => {
                    console.log(`${data}\n`)
                })
            }
            execRes.on('close', (code) => {
                reslove(code)
            })
            execRes.on('error', (err) => {
                reject(err)
            })
        } else {
            const execRes = spawn(command, [...args], {
                encoding: 'UTF-8'
            })
            if (output) {
                execRes.stdout.on('data', (data) => {
                    console.log(`${data}\n`)
                })
                execRes.stderr.on('data', (data) => {
                    console.log(`${data}\n`)
                })
            }
            execRes.on('close', (code) => {
                reslove(code)
            })
            execRes.on('error', (err) => {
                reject(err)
            })
        }
    })
}

const urlParamsProcess = (url) => {
    let param = {}
    url.replace(/([^?&]+)=([^?&]+)/g, (s, v, k) => {
        param[v] = decodeURIComponent(k)
        return k + '=' + v
    })
    return param
}

exports.uuid = uuid
exports.readFile = readFile
exports.writeFile = writeFile
exports.runShell = runShell
exports.urlParamsProcess = urlParamsProcess